'use strict';

const _  = require('lodash');

//防抖动
const debounceTestBefore = _.debounce(function () {
    console.log("Function execute.Before debounce." + (_.now() - start));
}, 2000, {
    leading: true,
    trailing: false,
});
let start = _.now();
debounceTestBefore();
debounceTestBefore();
debounceTestBefore();
debounceTestBefore();
debounceTestBefore();
console.log("在执行延迟前进行调用, 几乎不消耗时间。");

start = _.now();
const debounceTestAfter = _.debounce(function () {
    console.log("Function execute.After debounce." + (_.now() - start));
}, 2000, {
    leading: false,
    trailing: true,
});

debounceTestAfter();
debounceTestAfter();
debounceTestAfter();
debounceTestAfter();
debounceTestAfter();
console.log("在延迟后进行调用，会异步等待延迟结束。");

const debounceTestOverstep = _.debounce(function () {
    console.log("Function execute.Overstep debounce." + (_.now() - start));
}, 2000, {
    leading: false,
    trailing: true,
});

function overstepTest(func, count) {
    function ex() {
        func();
        setTimeout(function () {
            count--;
            if(count > 0) {
                overstepTest(func, count);
            }
        }, 100);
    }
    ex();
}
overstepTest(debounceTestOverstep, 50);
console.log("防抖动的作用可以理解为，函数必须休息wait时间以上才可以触发下一次执行。如果一系列频繁调用，业务认为只是一次调用。此次调用，连续5秒持续调用，加上延迟2秒，共7秒。");

//截流
start = _.now();
let time = 0;
const throttleTest = _.throttle(function () {
    time ++;
    console.log("Time: " + time + " throttle." + (_.now() - start));
}, 1000);

overstepTest(throttleTest, 100);
console.log("截流在规定的时间内最多执行1次，目前连续执行10秒钟，wait为1秒，理论上执行10次左右。");
